<template>
	<view class="container">
		<view class="topBer">
			<view class="status_bar" :style="{ height: statusBarHeight + 'px' }">
				
			</view>
			
			<view class="my_navBer">
				<view class="middle_navBer" @click="change">
					{{Nav[0][play_id].label}}
					<uni-icons color="#000" :type="nav_show?'top':'bottom'" size="38rpx" style="transition: all 0.5s;"></uni-icons>
				</view>
				
			</view>
		</view>
		<view class="nogame" v-if="shownodata">
			<view v-if="shownodata" style="width:100%;display: flex;justify-content: center;">
			<game></game>
			</view>
		</view>
		<classify :select_arr="tabsArr" @click_select="user_select"></classify>
		<view v-for="item,index in matchInfoList" :key="item.businessDate">
			
			<view v-show="tabsArr[showData_index].businessDate===item.businessDate">
				<view class="content_itme" v-for="item2,index2 in item.subMatchList" v-show="item2.MatchStatus=='Selling'" :key="index2">
					
					<view class="left">
						<view style="display:flex;flex-direction: column; margin: auto; text-align:center;">
							<view v-show="noshowdan(Nav[0][play_id].gameType,item2.PoolList)" style="justify-content: center; text-align: center;">
								<text class="dan_lable">单关</text>
							</view>
							<text style="margin: 2rpx;">{{item2.MatchNumStr}}</text>
							<text style="margin: 2rpx;">{{item2.LeagueAbbName}}</text>
							<text style="margin: 2rpx; color: #909399;">
								{{getNowFormatDate(3,item2.shopSetExpiration)}}:{{getNowFormatDate(5,item2.shopSetExpiration)}}截止
							</text>
							<text style="margin: 2rpx;color:#f04b49;" @click="sikp_scoer(item2.newMatchId)" v-show="item2.newMatchId">
								分析
							</text>
						</view>
					</view>
					<view class="right" style="display: flex;flex-direction: column;">
						<view class="right_title"
							style="">
							<view style="width: 45%; font-size: 30rpx;font-weight: bolder;">
								{{item2.HomeTeamAbbName}}
								<text :class="item2['HHAD'].GoalLine >0?'red':'green'"
									style="margin-left: 20rpx; font-size: 30rpx;font-weight: bolder;">
									{{item2['HHAD'].GoalLine}}</text>
							</view>
							<view style=" width: 10%;">
								<text style="font-size: 30rpx;">VS</text>
							</view>
							<view style="width: 45%; font-size: 30rpx;font-weight: bolder;">
								{{item2.AwayTeamAbbName}}
							</view>
						</view>
						<hhggcheckbox 
							v-if="play_id==0" :Refresh="forceRefresh" :fixSelectData="item2" 
							@getSelectList="
								getChildrenSelectList($event,getNowFormatDate(0,item2.shopSetExpiration))
							" 
							ref='childRef' 
						/>
												
						<spfcheckbox 
							v-if="play_id==1" :Refresh="forceRefresh" :fixSelectData="item2" 
							@getSelectList="
								getChildrenSelectList($event,getNowFormatDate(0,item2.shopSetExpiration))
							" 
							ref='childRef' 
						/>
						<crscheckbox 
							v-if="play_id==2" :Refresh="forceRefresh" :fixSelectData="item2" 
							@getSelectList="
								getChildrenSelectList($event,getNowFormatDate(0,item2.shopSetExpiration))
							" 
							ref='childRef' 
						/>
						<ttgcheckbox 
							v-if="play_id==3" :Refresh="forceRefresh" :fixSelectData="item2"
							@getSelectList="
								getChildrenSelectList($event,getNowFormatDate(0,item2.shopSetExpiration))
							" 
							ref='childRef' 
						/>
						<hafucheckbox 
							v-if="play_id==4" :Refresh="forceRefresh" :fixSelectData="item2" 
							@getSelectList="
								getChildrenSelectList($event,getNowFormatDate(0,item2.shopSetExpiration))
							" 
							ref='childRef' 
						/>
					</view>
				</view>
			</view>
		</view>

		<!-- 底部占位元素 - 高度与导航栏一致，避免最后一项被遮挡 -->
        <view class="footer-placeholder" v-if="showdata"></view>

		<!-- 底部导航 -->
		
		<view class="footer" style="" v-if="showdata">
			<Footer :isdan="isdan" :count="count" @clickbutton="onclickbutton()" @clickempty="initialization" />
		</view>
		<JarvisPicker mode="bottom" :show.sync="nav_show" :range="Nav" @confirm="confirm" @cancel="cancel" />
		<fuiDialog 
			:show="ShowTIPS" title="温馨提示" 
			content="暂时没有数据,可以去看看其他玩法哦 ; )" 
			:buttons="fuiButtons" :maskClosable='false' 
			@click='ShowTIPS=false'>
		</fuiDialog>
	</view>
</template>

<script>
	import game from '@/components/game.vue'
import {SportDataV1} from '@/api/public.js'
import hhggcheckbox from '@/components/jczq/new/hhgg-checkbox.vue';
import spfcheckbox from '@/components/jczq/new/spf-checkbox.vue';
import hafucheckbox from '@/components/jczq/new/hafu-checkbox.vue';
import ttgcheckbox from '@/components/jczq/new/ttg-checkbox.vue';
import crscheckbox from '@/components/jczq/new/crs-checkbox.vue';
// import {getNowFormatDate} from '@/common/getdatetime.js';
import fuiDialog from '@/components/fui-dialog/fui-dialog.vue';
import JarvisPicker from '@/components/common/jarvis-picker/jarvis-picker.vue';
import Footer from '@/components/jczq/footer.vue';
import classify from '@/components/classifySelect/classifySelect.vue';
import common from '@/common/common.js';
	import { mapState, mapMutations, mapActions } from 'vuex';
	import {chek} from '@/api/user.js'
export default {
  components: {
    hhggcheckbox,
    spfcheckbox,
    hafucheckbox,
    ttgcheckbox,
    crscheckbox,
    fuiDialog,
    JarvisPicker,
    Footer,
    classify,
	game
  },
  data() {
    return {
		showdata:false,
		shownodata:false,
		statusBarHeight:0,
      matchInfoList: [], // 比赛信息
      tabsArr: [], // tabs选择器数据
      showData_index: 0, // tabs默认选择值
      nav_show: false, // 顶部选择器弹窗是否显示
      systime: 5, // systime后续接入店铺自定义时间
      ShowTIPS: false, // 温馨提示显示控制
      fuiButtons: [ // 温馨提示的两个按钮
        {
          text: '好的退出',
          color: '#f04b49',
        }
      ],
      Nav: [ // 顶部选择器内容list
        [
          { label: '混合过关', value: 0, gameType: 'HAD' },
          { label: '胜平负', value: 1, gameType: 'HAD' },
          { label: '比分', value: 2, gameType: 'CRS' },
          { label: '总进球数', value: 3, gameType: 'TTG' },
          { label: '半全场', value: 4, gameType: 'HAFU' },
        ]
      ],
      play_id: 0, // nav玩法id
      count: 0, // 选择场次的数量
      isdan: true, // 是否单场
      forceRefresh: false, // 强制刷新标志
      localBettingContent: {
        type: '竞彩足球',
        gametype: '混合过关',
        remarks: [],
        Content: [],
        lssue: "",
      }
    };
  },
  onLoad() {
	chek().then(res=>{
				this.showdata = res.data;
				this.shownodata = !this.showdata;
			})
  	uni.getSystemInfo({ //获取系统信息
  		success: res => {
  			//  状态栏（顶部）高度
  			this.statusBarHeight = res.statusBarHeight

  		},
  		fail(err) {
  			console.log(err);
  		}
  	})
  },
			onShareAppMessage: function() {
				 return {
				 	title: this.miniHomeRemark,
				 	imageUrl: this.miniHomeImg,
				 	 path: '/pages/home/index'
				 };
				
			},
			onShareTimeline: function() {
				return {
					title: this.miniHomeRemark,
					imageUrl: this.miniHomeImg,
					path: 'pages/home/index'
				};
			},
  methods: {
	  getNowFormatDate(type, time) {
	  	if (time == null) {
	  		var date = new Date()
	  	} else {
	  		var date = new Date(time)
	  	}
	  
	  	var year = date.getFullYear() //获取完整的年份(4位)
	  	var month = date.getMonth() + 1 //获取当前月份(0-11,0代表1月)
	  	var strDate = date.getDate() // 获取当前日(1-31)
	  	var week = '星期' + '日一二三四五六'.charAt(date.getDay()) //获取当前星期几(0 ~ 6,0代表星期天)
	  	var hour = date.getHours() //获取当前小时(0 ~ 23)
	  	var minute = date.getMinutes() //获取当前分钟(0 ~ 59)
	  	var second = date.getSeconds() //获取当前秒数(0 ~ 59)
	  
	  	if (month >= 1 && month <= 9) month = '0' + month // 如果月份是个位数，在前面补0
	  	if (strDate >= 0 && strDate <= 9) strDate = '0' + strDate // 如果日是个位数，在前面补0
	  	if (minute >= 0 && minute <= 9) minute = '0' + minute // 如果分是个位数，在前面补0
	  	if (second >= 0 && second <= 9) second = '0' + second // 如果秒是个位数，在前面补0
	  
	  	// 根据type值返回指定格式
	  	if (type == 0) { //yyyy-mm-dd hh:mm:ss
	  		let currentdate = `${year}-${month}-${strDate} ${hour}:${minute}:${second}`
	  		return currentdate
	  	}
	  	if (type == 1) { //yyyy-mm-dd
	  		let currentdate = `${year}-${month}-${strDate}`
	  		return currentdate
	  	}
	  	if (type == 2) { //hh:mm:ss
	  		let currentdate = `${hour}:${minute}:${second}`
	  		return currentdate
	  	}
	  	if (type == 3) { //hh
	  		let currentdate = `${hour}`
	  		return currentdate
	  	}
	  	if (type == 4) { //-mm-dd
	  		let currentdate = `${month}-${strDate}`
	  		return currentdate
	  	}
	  	if (type == 5) { //mm
	  		let currentdate = `${minute}`
	  		return currentdate
	  	}
	  },
    change() {
      this.nav_show = true;
    },
    cancel() {
      this.nav_show = false;
    },
    confirm(e) {
      this.nav_show = false;
      this.play_id = this.Nav[0][e[0]].value;
      this.initialization();
    },
    user_select(e) {
      this.showData_index = e;
    },
    onclickbutton() {

      this.localBettingContent.Content = this.localBettingContent.Content.sort((a, b) => a.matchId - b.matchId);

	  this.$store.dispatch('updateSharedData', this.localBettingContent);
      if (this.count === 0) {
        uni.showToast({
          icon: 'error',
          title: '请选择比赛',
          duration: 2000
        });
        return;
      }
      if (this.count === 1 && !this.isdan) {
        uni.showToast({
          icon: 'error',
          title: '还需再选1场',
          duration: 2000
        });
      } else {
        uni.navigateTo({
          url: '/pages/submit/submit_ticai',
          animationType: 'pop-in',
          animationDuration: 200,
        });
      }
    },
    initialization() {
      this.count = 0;
      this.forceRefresh = !this.forceRefresh;
      this.localBettingContent.Content = [];
      this.tabsArr.forEach(tab => tab.selectNumber = 0);
    },
  //   getChildrenSelectList(data, time) {
  //     data.gameData.orderDeadline = time; // 投注截止时间赋值
  //     if (data.selectBoole) {
  //       if (this.localBettingContent.Content.length === 0) {
  //         this.count++;
  //         this.tabsArr[this.showData_index].selectNumber++;
  //         this.localBettingContent.Content.push(data.gameData);
  //       } else {
  //         let index = this.localBettingContent.Content.findIndex(item => item.matchId === data.gameData.matchId);
  //         if (index === -1) {
  //           this.count++;
  //           this.tabsArr[this.showData_index].selectNumber++;
  //           this.localBettingContent.Content.push(data.gameData);
  //         } else {
  //           this.localBettingContent.Content[index] = data.gameData;
  //         }
  //       }
  //     } else {
  //       this.count--;
  //       this.tabsArr[this.showData_index].selectNumber--;
  //       let index = this.localBettingContent.Content.findIndex(item => item.matchId === data.gameData.matchId);
		// console.log(this.localBettingContent.Content)
  //       this.localBettingContent.Content.splice(index, 1);
  //     }

      // this.localBettingContent.Content.forEach(game => {
      //   game.data.forEach(pool => {
      //     if (pool.poolEs === 0) {
      //       this.isdan = false;
      //       return;
      //     }
      //   });
      //   if (!this.isdan) return;
      //   this.isdan = true;
      // });
  //   },
  getChildrenSelectList(data, time) {
    data.gameData.orderDeadline = time; // 投注截止时间赋值
  
    if (data.selectBoole) {
      // 添加或更新投注内容
      const existingIndex = this.localBettingContent.Content.findIndex(item => item.matchId === data.gameData.matchId);
      if (existingIndex === -1) {
        // 不存在，添加新内容
        this.count++;
        this.tabsArr[this.showData_index].selectNumber++;
        this.localBettingContent.Content.push(data.gameData);
      } else {
        // 存在，更新内容
        this.localBettingContent.Content[existingIndex] = data.gameData;
      }
    } else {
      // 删除投注内容
      const index = this.localBettingContent.Content.findIndex(item => item.matchId === data.gameData.matchId);
      if (index !== -1) {
        this.count--;
        this.tabsArr[this.showData_index].selectNumber--;
        this.localBettingContent.Content.splice(index, 1);
      }
    }
  
    // 检查投注内容   true 可单关
    this.isdan = this.localBettingContent.Content.every(game => {
	console.log(game.data)
      return !game.data.some(pool =>   (pool.poolEs === 0 && ['rq'].includes(pool.gameState)) || (pool.poolEs === 0   && ['spf'].includes(pool.gameState)) ) ;
    });

  },
    getjiezhitime(businessDate, matchDate, week, matchTime) {
      let sbIphone = businessDate.replace(/-/g, '/');
      let newBusinessDate = new Date(sbIphone); // 投注截止日期
      let newMatchDate = new Date(matchDate.replace(/-/g, '/') + ' ' + matchTime); // 比赛日期拼接比赛时间赋值完整的比赛时间戳

      let nowHours = week === '周日' || week === '周六' ? 23 : 22; // 当前周对应的投注截止时间中的小时
      newBusinessDate.setHours(nowHours);

      if (newMatchDate.getTime() > newBusinessDate.getTime()) {
        return newBusinessDate.setMinutes(newBusinessDate.getMinutes() - this.systime);
      } else {
        return newMatchDate.setMinutes(newMatchDate.getMinutes() - this.systime);
      }
    },
    noshowdan(nowGame, allGameList) {
      if (allGameList[nowGame] && allGameList[nowGame].BettingSingle === 1) {
        return true;
      }
      return false;
    },
    deleStyle() {
      this.tabsArr.forEach(tab => {
        let findBoole = tab.selectGameArr.includes(this.$store.state.counter.styleData.data[0]);
        if (findBoole) {
          tab.selectNumber--;
          return;
        }
      });

      this.$refs.childRef.forEach(ref => {
        if (ref.deleteId === this.$store.state.counter.styleData.data[0]) {
          ref.init();
          return;
        }
      });

      this.localBettingContent.Content = this.$store.state.counter.localBettingContent.Content;
      this.count = this.localBettingContent.Content.length;
      this.$store.commit('setStyleData', []);
    },
    handleTIPSClick(index) {
      if (index === 0) {
        this.ShowTIPS = false;
        uni.navigateBack();
      }
    },
    back() {
      uni.navigateBack();
    },

    gameDataInit(data) {
      let copyData = JSON.parse(JSON.stringify(data)); // 数据克隆
      let userNowTime = new Date().getTime(); // 用户当前时间
      copyData.forEach(itme => {
        let newGameData = [];
        let gameIdArr = [];
		 console.log("》》》》》》itme.SubMatchList",itme.SubMatchList)
        itme.SubMatchList.forEach(match => {
          match['shopSetExpiration'] = this.getjiezhitime(itme.BusinessDate, match.MatchDate, match.MatchWeek, match.MatchTime);
          if (userNowTime < match['shopSetExpiration']) {
			  
			  console.log("userNowTime < match['shopSetExpiration']")
            gameIdArr.push(match.MatchId);
            newGameData.push(match);
            let newPoolList = {};
            match.PoolList.forEach(pool => {
              newPoolList[pool.PoolCode] = {
                BettingSingle: pool.BettingSingle,
                PoolId: pool.PoolId,
                Single: pool.Single
              };
            });
            match.PoolList = newPoolList;
          }
        });
        let newObj = {
          businessDate: itme.BusinessDate,
          subMatchList: newGameData,
        };
        let tbas = {
          businessDate: itme.BusinessDate,
          matchNumber: itme.MatchCount,
          weekday: itme.Weekday,
          selectNumber: 0,
          selectGameArr: gameIdArr,
        };
        if (newGameData.length > 0) {
          this.matchInfoList.push(newObj);
          this.tabsArr.push(tbas);
        }
      });
	
	   uni.setStorageSync("showdata",this.showdata);
      uni.hideLoading();
	 
    },
    onBeforeMount() {
      this.matchInfoList = []; // 初始化数据
      uni.showLoading({ title: '数据获取中', mask: true });

      uni.request({
        url: 'https://api.jxchzj.cn/shop-api/sportDataV1',
        method: 'get',
        success: (res) => {
          uni.hideLoading();
          if (res.statusCode === 200) {
            if (res.data.list.length === 0) {
              this.ShowTIPS = true;
              return;
            }
			uni.setStorageSync("isAdult",1)
			console.log("》》》》》》",res.data.list)
            this.gameDataInit(res.data.list);
          }
          if (this.matchInfoList.length === 0) {
            this.ShowTIPS = true;
          }
		 
		   uni.setStorageSync("showdata",this.showdata);
        },
        fail: (err) => {
          uni.hideLoading();
          uni.showToast({
            title: '数据处理失败~',
            icon: 'none',
            position: 'center',
          });
        }
      });
    }
  },
  watch: {
    // 'counter.styleData.data.length': function(newValue, oldValue) {
    //   if (newValue > 0) {
    //     this.deleStyle();
    //   }
    // }
  },
  created() {
    this.onBeforeMount();
  }
};
</script>
<style lang="scss">
.container{
	background-color: #ff4242;
}
	.my_navBer{
		width:100%;
		height:90rpx;
		display: flex;
		align-items: center;
		padding:0rpx 20rpx;
		box-sizing: border-box;
		background-color: #ff4242;
		
		.middle_navBer{
			text-align: center;
			font-weight: bold;
			color: #ffffff;
		}
		view{
			flex:1;
		}
	}
	.right_title{
		display: flex;
		flex-direction: row;
		margin-top: 20rpx;
		align-items: center;
		justify-content: center;
		text-align: center;
	}
	.dan_lable{
		background-color: #ff0000;
		color: #FFFFFF;
		padding:5rpx;
		border-radius:10rpx;
		font-size:26rpx;
	}
	.content_box{
		margin-bottom: 100rpx;
	}
	.content_itme{
		display: flex;
		width:720rpx;
		margin:0rpx auto 15rpx auto;
		background-color:white;
		border-radius:15rpx;
		box-shadow:0px 5rpx 15rpx 5rpx rgba(226, 226, 226, 0.4);
	}
	body{
		background-color:#fbfbfb;
	}
	.buttomStyle{
		width:100%;
		height:80rpx;
		background-color:#f04b49;
		border-radius:15rpx;
		text-align: center;
		line-height:80rpx;
		color: white;
	}
	.userCard{
		width:680rpx;
		padding:20rpx;
		background-color:white;
		border-radius:20rpx;
		font-size:32rpx;
		max-height:1200rpx;
		line-height:60rpx;
		margin:20rpx 0;
	}
	.topBer{
		z-index:999;
		position: -webkit-sticky;
		position: sticky;
		top:0rpx;
		background-color:#ff4242;
		
	}
	.statusBar{
		width:100%;
		height: var(--status-bar-height);
		background-color: #ff4242;
		z-index:999;
	}
	.right .red {
		color: red;
	}

	.right .green {
		color: green;
	}

	.left {
		width: 20%;
		display: -webkit-box;
		-webkit-box-orient: horizontal;
		-webkit-box-pack: center;
		-webkit-box-align: center;
		/* 边框 */
		border-right:1rpx solid #edf0f3;
		-webkit-box-sizing: border-box;
		box-sizing: border-box;
	}
	.right {
		width: 80%;
		/* 边框 */
		-webkit-box-sizing: border-box;
		box-sizing: border-box;
	}
	.footer {
		position: fixed;
		bottom: 0;
		left: 0;
		width: 100%;
	}
	  // 底部占位元素 - 高度与导航栏一致
	  .footer-placeholder {
            height: 100rpx; /* 与导航栏高度保持一致 */
            clear: both;
        }
	.box-bg {
		display: flex;
		flex-direction: column;
		width: 100%;
		/* background-color: #F5F5F5; */
		margin-bottom: 30rpx;
	}
	.nogame {
		width: 100%;
		position: fixed;
		// top:calc(50% - 350rpx);
		// left:calc(50% - 250rpx);
	}
</style>